<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item :label="$t('发放时间')">
              <a-date-picker
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_begin"
              ></a-date-picker>
              <span class="query-group-split-cust"></span>
              <a-date-picker
                :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择结束时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_end"
              ></a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('会员信息')">
              <a-input :placeholder="$t('请输入会员手机号/卡号/姓名')" v-model="queryParam.memberInfo"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('券信息')">
                <a-input :placeholder="$t('请输入券号/名称')" v-model="queryParam.couponInfo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="10" :lg="11" :md="12" :sm="24">
              <a-form-item :label="$t('核销时间')">
                <a-date-picker
                  :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择开始时间')"
                  class="query-group-cust"
                  v-model="queryParam.updateTime_begin"
                ></a-date-picker>
                <span class="query-group-split-cust"></span>
                <a-date-picker
                  :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择结束时间')"
                  class="query-group-cust"
                  v-model="queryParam.updateTime_end"
                ></a-date-picker>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('状态')">
                <a-select v-model="queryParam.state">
                  <a-select-option :value="item.value" :key="index" v-for="(item, index) in couponStateList">{{
                    item.title
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('发放类型')">
                <a-select v-model="queryParam.getType">
                  <a-select-option :value="item.value" :key="index" v-for="(item, index) in couponTypeList">{{
                    item.title
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="8" :lg="9" :md="10" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <div class="table-operator">
      <a-button v-has="'BisMemberCouponController:export'" type="primary" icon="download" @click="handleExportXls($t('优惠券信息'))">{{ $t('导出') }}</a-button>
      <a-button v-has="'BisMemberCouponController:import'" type="primary" icon="import" @click="getImport">{{ $t('导入') }}</a-button>
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            {{ $t('下载') }}
          </a-button>
        </template>
      </a-table>
    </div>
    <!-- 导入弹窗 -->
    <a-modal
      :title="$t('导入优惠券')"
      :visible="visible"
      :destroyOnClose="destroyOnClose"
      :confirm-loading="confirmLoading"
      :okText="$t('确定')"
      :cancelText="$t('取消')"
      :width="modal_width"
      :cancel-button-props="cancelbutton"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :spinning="confirmLoading" style="padding: 0 20px">
        <a-row style="margin-bottom: 20px">
          <a-col>
            <span style="opacity: 0">*</span><span style="color: #666">{{ $t('导入模板') }}：</span>
            <a-button type="primary" icon="download" @click="handleExportXls1($t('年票次票导入模板'))">{{
              $t('下载模板')
            }}</a-button>
          </a-col>
        </a-row>
        <a-row style="margin-bottom: 20px">
          <a-col>
            <span style="color: #f00">*</span><span style="color: #666">{{ $t('导入文件') }}：</span>
            <a-input
              style="width: 400px; margin-right: 6px; vertical-align: bottom"
              :placeholder="$t('请选择要导入的优惠券信息文件')"
              disabled
              v-model="filename"
            ></a-input>
            <a-upload
              name="file"
              accept=".xls, .xlsx"
              :fileList="fileList"
              :showUploadList="false"
              :multiple="false"
              :headers="tokenHeader"
              :remove="handleRemove"
              :beforeUpload="beforeUpload"
              :customRequest="customRequest"
            >
              <a-button style="background: #f59b1e; color: #fff; border-color: #f59b1e">
                {{ $t('选择') }}
              </a-button>
            </a-upload>
          </a-col>
        </a-row>
      </a-spin>
    </a-modal>
  </a-card>
</template>

<script>
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, UploadFile, postAction, downFile } from '@/api/manage'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import Vue from 'vue'

export default {
  name: 'CouponsList',
  components: {},
  data() {
    return {
      description: '商品销售管理页面',
      moment,
      queryParam: {
        memberInfo: '',
        state: '',
        getType: '',
        updateTime_begin: '',
        updateTime_end: '',
        couponInfo: '',
        column: 'createTime',
        order: 'desc',
      },
      // 表头
      columns: [
        {
          title: this.$t('券号'),
          align: 'center',
          dataIndex: 'id',
        },
        {
          title: this.$t('券名称'),
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: this.$t('面额'),
          align: 'center',
          dataIndex: 'value',
          customRender: (text, r) => {
            return r.value.toFixed(2)
          },
        },
        {
          title: this.$t('状态'),
          align: 'center',
          dataIndex: 'state_dictText',
        },
        {
          title: this.$t('有效期'),
          align: 'center',
          dataIndex: 'time',
        },
        {
          title: this.$t('手机号'),
          align: 'center',
          dataIndex: 'memberPhone',
        },
        {
          title: this.$t('卡号'),
          align: 'center',
          dataIndex: 'chipNo',
        },
        {
          title: this.$t('姓名'),
          align: 'center',
          dataIndex: 'memberName',
        },
        {
          title: this.$t('发放时间'),
          align: 'center',
          dataIndex: 'createTime',
        },
        {
          title: this.$t('发放类型'),
          align: 'center',
          dataIndex: 'getType_dictText',
        },
        {
          title: this.$t('核销时间'),
          align: 'center',
          dataIndex: 'updateTime',
        },
      ],
      url: {
        list: '/member/bisMemberCoupon/list',
        delete: '/member/bisMemberCoupon/delete',
        exportXlsUrl: '/member/bisMemberCoupon/exportXls',
        importExcelUrl: 'sys/common/upload',
      },
      dictOptions: {
        payType: [],
      },
      couponStateList: [],
      couponTypeList: [],
      deviceList: [],
      userList: [],
      dataSource: [],
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 16 },
      },
      loading: false,
      toggleSearchStatus: true,
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total', { total: total })
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onShowSizeChange: (current, pageSize) => this.handleSizeChange(current, pageSize),
      },
      // 导入弹窗
      visible: false,
      fileList: [],
      filename: '',
      destroyOnClose: true,
      confirmLoading: false,
      cancelbutton: { props: { disabled: false } },
      modal_width: '700px',
      ruleForm: {
        filename: '',
        name: '',
      },
      exloading: false,
    }
  },
  created() {
    this.loadData(1)
    this.initDictConfig()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    },
  },
  methods: {
    initDictConfig() {
      initDictOptions('bis_member_coupon.state').then((res) => {
        if (res.success) {
          this.couponStateList = res.result
          this.couponStateList.unshift({ value: '', title: this.$t('全部') })
        }
      })
      initDictOptions('bis_member_coupon.get_type').then((res) => {
        if (res.success) {
          this.couponTypeList = res.result
          this.couponTypeList.unshift({ value: '', title: this.$t('全部') })
        }
      })
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    loadData(arg) {
      this.dataSource = []
      if (!this.url.list) {
        this.$message.error(this.$t('请设置url.list属性'))
        return
      }
      this.ipagination.current = arg
      this.queryParam.pageNo = this.ipagination.current
      this.queryParam.pageSize = this.ipagination.pageSize
      var params = this.queryParam
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            res.result.records.forEach((col) => {
              if (col.validityStart == undefined || col.validityStart == null) {
                col.time = this.$t('不限期')
              } else {
                col.time = col.validityStart + '~' + col.validityEnd
              }
              if (col.state != '3') {
                col.updateTime = ''
              }
              this.dataSource.push(col)
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize
    },
    handleTableChange(pagination, filters, sorter) {
      this.loadData(pagination.current)
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      let that = this
      that.fileList = [file]
      that.filename = file.name
      return false
    },
    customRequest(data) {
      // 上传提交
      let that = this
      that.fileList = [data.file]
    },
    searchQuery() {
      if (this.queryParam.updateTime_begin != '') {
        this.queryParam.state = '3'
      }
      this.loadData(1)
    },
    searchReset() {
      this.queryParam = {
        memberInfo: '',
        state: '',
        getType: '',
        updateTime_begin: '',
        updateTime_end: '',
        couponInfo: '',
        column: 'createTime',
        order: 'desc',
      }
      this.loadData(1)
    },
    showModal(record) {
      this.$refs.typeNameForm.edit(record)
    },
    getImport() {
      this.visible = true
      this.ruleForm = {
        filename: '',
        name: '',
      }
    },
    //下载模板
    download(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let url = window._CONFIG['domianURL'] + 'importTemplate/电子优惠券导入模板.xls'
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
      return
    },
    handleExportXls(fileName) {
      this.exloading = true
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('导出文件')
      }
      let param = this.queryParam
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param)
        .then((data) => {
          if (!data) {
            this.$message.warning(this.$t('文件下载失败'))
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
        .finally(() => {
          this.exloading = false
        })
    },
    //导入
    handleExportXls1(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let url = window._CONFIG['domianURL'] + 'importTemplate/电子优惠券导入模板.xls'
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
      return
    },
    /**
     * 弹窗确定
     */
    handleOk() {
      let that = this
      const { fileList } = that
      if (fileList.length == 0) {
        that.$message.warning(this.$t('请选择要导入的优惠券文件'))
        return
      }
      const formData = new FormData()
      fileList.forEach((file) => {
        formData.append('files[]', file)
      })
      that.confirmLoading = true
      postAction('/member/bisMemberCoupon/importExcel', formData)
        .then((res) => {
          if (res.success) {
            if (res.code == 201) {
              that.errorTip(res.message, res.result)
            } else {
              that.$message.success(res.message)
            }
            that.visible = false
            that.$emit('ok')
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    /**
     * 弹窗取消
     */
    handleCancel(e) {
      this.visible = false
      this.$refs.ruleForm.resetFields()
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>